#!/usr/bin/env python
#_*_ coding:utf-8 _*_

import re
from model.collect import GameList, GameDetail
from pyscript.core.url import realUrl


class DangleList(GameList):

    def parseData(self, baseUrl = None):
        retval = dict()
        retval['next'] = self.nextUrl(baseUrl)
        retval['games'] = self.itemList(baseUrl)
        return retval


    def nextUrl(self, baseUrl = None):
        pyQueryDom = self.pq(self.body) 
        nextLable = pyQueryDom("div#list div.pager a:nth-last-child(1)")
        url = None

        if u'下一页' == nextLable.text().decode('utf-8'):
            url = realUrl(nextLable.attr("href"), base = baseUrl)

        return url


    def gameDetail(self, url, base=None):
        model = DangleGameDetailList(timeout=self.timeout, retry = self.retry, sleep = self.sleep, header = self.headers)
        model.fopen(url)
        return model.getData()


    def itemList(self, baseUrl = None):
        retval = []
        pyQueryDom = self.pq(self.body)
        gameLables = pyQueryDom("div#list div.game_soft div.gamesoft_info")

        for item in gameLables:
            link_element = self.pq(item)("a.gamesoft_link")
            url = realUrl(link_element.attr('href'), base = baseUrl)
            game = self.gameDetail(url, baseUrl)

            if not isinstance(game, dict):
                continue

            title = link_element.attr('title')
            m, version = re.search('[vV](?P<version>\d[.\d]+\d)', title), '0.0.1'

            if m:
                m = m.groupdict()
                version = m.get('version', u'0.0.1').strip()

            game['version'] = version
            retval.append(game)

        return retval


class DangleGameDetailList(GameDetail):

    def parseData(self, baseUrl = None):
        retval = dict()
        title = 'unknown'
        titleText = self.pq(self.body)('div#info-main div.pr h1.app-title').text().strip()
        m = re.search('^(?P<title>[^vV]*)[vV][\d.]*\d$', titleText)

        if m:
            m = m.groupdict()
            title = m.get('title', u'').strip()

        retval['name'] = title
        return retval

